<template>
  <Dialog width="910px" :title="title" :visible.sync="innerVisible">
    <el-row>
      <el-col :span="24">
        <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="110px">
          <Portlet title="厂家信息">
            <el-row :gutter="15">

              <el-col :span="12">
                <el-form-item label="厂家名称" prop="manufacturersName" :rules="[
                    {required: true, message: '厂家名称必须', trigger: 'blur'}
                  ]">
                  <el-input v-model="model.manufacturersName" :disabled="id?true:false"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="厂家联系人" prop="manufacturersUserName" :rules="[
                  ]">
                  <el-input v-model="model.manufacturersUserName"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="厂家联系电话" prop="manufacturersUserPhone" :rules="[
                  {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                ]">
                  <el-input v-model="model.manufacturersUserPhone"></el-input>
                </el-form-item>
              </el-col>

              <!--<el-col :lg="8" :md="12" :xl="6">-->
                <!--<el-form-item label="所属公司名称" prop="companyId">-->
                  <!--<el-select-->
                    <!--v-model="model.companyId"-->
                    <!--filterable-->
                    <!--clearable-->
                    <!--placeholder="请输入关键词"-->
                    <!--remote-->
                    <!--:remote-method="remoteQuery"-->
                    <!--:loading="cargoOwnerLoading">-->
                    <!--<el-option-->
                      <!--v-for="item in cargoOwnerArr"-->
                      <!--:key="item.value"-->
                      <!--:label="item.text"-->
                      <!--:value="item.value">-->
                    <!--</el-option>-->
                  <!--</el-select>-->
                <!--</el-form-item>-->
              <!--</el-col>-->

              <el-col :span="12">
                <el-form-item label="厂家地址" prop="addressArr" :rules="[
              ]">
                  <CascadeAddress v-model="model.addressArr" :level="3"/>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="详细地址"  prop="address" :rules="[
              ]">
                  <el-input type="textarea" :maxlength="200" v-model="model.address"/>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>

          <!--<Portlet>-->
            <!--<el-row :gutter="15">-->
              <!--<el-col :span="24" class="text-center">-->
                <!--<el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">-->
                  <!--{{ id ? '保存' : '新增'}}-->
                <!--</el-button>-->
              <!--</el-col>-->
            <!--</el-row>-->
          <!--</Portlet>-->
        </el-form>
      </el-col>
    </el-row>

    <div slot="footer">
      <el-button @click="innerVisible = false">关闭窗口</el-button>
      <el-button type="primary" :loading="loading" @click="submit">{{ id ? '保存' : '新增'}}</el-button>
    </div>

  </Dialog>
</template>
<script>

import {copy, dotData, alert, confirm} from '@/utils'
import {isFormatNumber, isPhone} from '@/utils/validate'
import L from 'lodash'

export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  watch: {
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        // // 重置表单
        this.resetFields()
        // 获取数据
        if (this.id) {
          this.getDetail()
        }
      }
      this.innerVisible = val
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    }
  },
  data() {
    return {
      // id: this.$route.params.id,
      innerVisible: this.visible,
      routeName: this.$route.name,
      loading: false,
      cargoOwnerLoading: false,
      model: {
        manufacturersName: '',
        manufacturersUserName: '',
        manufacturersUserPhone: '',
        companyId: '',
        addressArr: [],
        address: ''
      },
      cargoOwnerArr: []
    }
  },
  // created() {
  //   if (this.id) {
  //     this.getDetail()
  //   }
  // },
  methods: {
    isFormatNumber,
    isPhone,
    getDetail() {
      // 获取详情信息
      this.$ajax.get('/ms-warehouse-order/basicData/findManufacturersInfo', {manufacturersId: this.id}).then(response => {
        if (!response.data) {
          return
        }
        this.model.manufacturersName = dotData(response, 'data.manufacturersName')
        this.model.manufacturersUserName = dotData(response, 'data.manufacturersUserName')
        this.model.manufacturersUserPhone = dotData(response, 'data.manufacturersUserPhone')
        this.model.companyId = dotData(response, 'data.companyId')
        if (this.model.companyId) {
          this.cargoOwnerArr = [
            {text: dotData(response, 'data.companyName'), value: this.model.companyId}
          ]
        }
        this.model.address = dotData(response, 'data.address')
        // 回填地址数据
        let addressArr = []
        if (dotData(response, 'data.provinceNo')) {
          addressArr.push(dotData(response, 'data.provinceNo'))
          if (dotData(response, 'data.cityNo')) {
            addressArr.push(dotData(response, 'data.cityNo'))
            if (dotData(response, 'data.districtNo')) {
              addressArr.push(dotData(response, 'data.districtNo'))
            }
          }
        }
        this.model.addressArr = addressArr
      })
    },
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.operation = 'update'
        data.id = this.id
      } else {
        data.operation = 'insert'
      }
      // 省市区处理
      if (Array.isArray(data.addressArr)) {
        data.provinceNo = dotData(data.addressArr, 0)
        data.cityNo = dotData(data.addressArr, 1)
        data.districtNo = dotData(data.addressArr, 2)
        delete data.addressArr
      }
      return this.$ajax.post(url, data).then(response => {
        return response
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '编辑成功' : '新增成功'
        let url = '/ms-warehouse-order/basicData/operateManufacturersInfo'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            confirm(title, title, {
              type: 'success',
              showCancelButton: false,
              closeOnClickModal: false
            }).finally(_ => {
              // this.$router.push({path: '/redirect/ss-oms/basic-data/manufactor/index'})
              this.innerVisible = false
              this.resetFields()
              this.loading = false
              this.$emit('refresh')
            })
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      try {
        const elForm = this.$refs.elForm
        if (elForm) {
          this.$refs.elForm.resetFields()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 后端搜索
    remoteQuery(query) {
      this.cargoOwnerLoading = true
      this.remoteMethod(query, this)
    },
    // 后端搜索 函数防抖
    remoteMethod: L.debounce((query, _this) => {
      if (!query) {
        _this.cargoOwnerLoading = false
        return
      }
      _this.$ajax.get('/ms-warehouse-order/basicData/findCompanyList', {name: query}).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            data.forEach((v, k) => {
              tempArr.push({
                text: v.name,
                value: v.id
              })
            })
          }
          _this.cargoOwnerArr = tempArr
        }
      }).finally(_ => {
        _this.cargoOwnerLoading = false
      })
    }, 1000)
  }
}
</script>
